from conan import ConanFile
from conan.tools.cmake import CMakeToolchain, CMake, cmake_layout,CMakeDeps
from conan.tools.files import copy, get,chdir
from conan.tools.gnu import Autotools, AutotoolsToolchain
import os
class SampleRecipe(ConanFile):
    name = "test" # Example: "spdlog" ,small letter
    version = "1.0" # Example: "1.8.5"
    license = "{{ license }}"  # Example: "MIT"
    author = "{{ author }}"  # Example: "Gabriel Melman"
    url = "{{ url }}"  # Example: "https://github.com/gabime/spdlog"
    description = "{{ description }}"  # Example: "Fast C++ logging library."
    topics = ("{{ topics }}")  # Example: ("C++", "logging", "library", "spdlog")
    settings = "os", "compiler", "build_type", "arch"  # Standard settings
    options = {"shared": [True, False], "fPIC": [True, False],"usr_mode" : ["cmake", "autotools"]}  # options of the package
    default_options = {"shared": False, "fPIC": True , "usr_mode" : "cmake"}  # default options of the package
    #exports_sources = "/home/hello"  #source_src的作用只是拷贝,并且是从主目录考虑的,操作不透明,目前不使用.使用copy()方法代替这份功能    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.build_mode = "cmake"   
        self.work_dir = ""
    def source(self):
        self.output.info("self.source_folder = " + self.source_folder)
        # 手动拷贝需要的源码工程
        pattern = "*"
        # 这个变量会在create_lib.sh脚本中被替换
        source_src = "/home/hello"
        copy(self, pattern=pattern, src=source_src, dst=self.source_folder) 
        #self.work_dir = os.path.join(self.source_folder, "subfolder")
    # def requirements(self):
    #     self.requires("libiconv/1.17")

    def config_options(self):
        if self.settings.os == "Windows":
            del self.options.fPIC # Windows does not require -fPIC flag

    def layout(self):
        self.folders.source = "hello/" # 它的作用只是指定本地缓存的源码目录,这个变量会在create_lib.sh脚本中被替换
        self.folders.build = "build"
        self.output.info("self.folders.source = " + self.folders.source)
        self.output.info("os.getcwd() = " + os.getcwd())
        # with chdir(self.recipe_folder, self.folders.source):

        #     self.output.info("os.listdir() = " + str(os.listdir())) 

    def generate(self):# third step
        self.detect_build_system()
        self.output.info("generate pwd = " + os.getcwd())
        if self.build_mode == "cmake":
            tc = CMakeToolchain(self)
            tc.generate()
            tc.variables["BUILD_SHARED_LIBS"] = "ON" if self.options.shared else "OFF"
            if self.settings.os != "Windows":
                tc.variables["CMAKE_POSITION_INDEPENDENT_CODE"] = "ON" if self.options.fPIC else "OFF"
            deps = CMakeDeps(self)
            deps.generate()
        elif self.build_mode == "autotools":
            tc = AutotoolsToolchain(self)
            tc.generate()
        else:
            raise Exception("No build system found. Please provide a CMakeLists.txt or a configure script.")


    def build(self):
        self.output.info(" build pwd = " + os.getcwd())    
        if self.build_mode == "cmake":
            self.output.info("执行 CMake 构建流程")
            cmake = CMake(self)
            if self.work_dir:
                cmake.configure(build_script_folder=self.work_dir)
            else:
                cmake.configure()
            cmake.build()
        elif self.build_mode == "autotools":    
            with chdir(self, self.source_folder):
                autotools = Autotools(self)
                autotools.configure(args=["--prefix={}".format(self.package_folder)])
                autotools.make()    
    def package(self):
        self.output.info(" package pwd = " + os.getcwd())    
        if self.build_mode == "cmake":
            cmake = CMake(self)
            cmake.install()
        elif self.build_mode == "autotools":  
            with chdir(self, self.source_folder):
                autotools = Autotools(self)
                autotools.install()
        else:
            self.output.error("build_mode = " + self.build_mode)
    def package_info(self):
        self.cpp_info.libs = ["test"] # Example: ["spdlog"]
    def detect_build_system(self):
        cmake_file_path = os.path.join(self.source_folder, "CMakeLists.txt")
        
        if os.path.exists(cmake_file_path):
            self.output.info("CMakeLists.txt exists: Yes")
        elif os.path.exists(os.path.join(self.source_folder, "configure")):
            self.build_mode = "autotools"
            self.output.info("configure exists: Yes")
            # 如果不加权限,configure()方法有可能无法执行
            os.chmod(os.path.join(self.source_folder, "configure"), 0o755)
        else: #目前只处理 CMakeLists.txt 和 configure
            self.output.error("CMakeLists.txt exists: No")
            self.output.error("configure exists: No")
            self.build_mode = str(self.options.usr_mode)
            self.output.info("build_mode = " + self.build_mode)
            # raise Exception("No build system found. Please provide a CMakeLists.txt or a configure script.")   